package com.hncj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hncj.pojo.Image;
import com.hncj.result.R;
import com.hncj.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/upload/image")
public class imageController {

    @Autowired
    private ImageService imageService;
    @Value("${MyBlog.path}")//千万别用path，这是已有的配置，不是自定义的
    private String basePath;
    @Value("${Service.address}")
    private String baseService;

    @GetMapping("/list")
    public R<List<Image>> getList(){
        return R.success(imageService.list());
    }

    @DeleteMapping
    public R<String> deleteImageByName(@RequestBody String[] names){

        List<Image> namesImage = imageService.getNamesImage(names);

        for (Image image: namesImage) {
            String path = image.getAddress();
            try {
                Files.delete(Paths.get(path));
                System.out.println("图片删除路径:"+Paths.get(path));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        boolean remove = imageService.removeImages(names);//数据库删除失败 改用mapper

        return remove?R.success("删除出错！") : R.error("删除成功！");
    }

    @PostMapping("/{id}")
    public R<String> uploadImageOfArticle(@PathVariable("id") Integer id,@RequestBody Integer []ids){

        Image image = new Image();
        image.setDependenceId(id);

        for(Integer idImage : ids){
            image.setId(idImage);
            imageService.updateById(image);
        }

        return R.success("图片从属关系已更新！");

    }

    @PostMapping
    public R<String[]> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        //后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //判断是否存在目录basePath
        File dir=new File(basePath);

        //如果不存在就创建目录
        if(!dir.exists()){
            dir.mkdirs();
        }

        //UUID重命名文件,防止文件名称重复造成文件覆盖
        String fileName= UUID.randomUUID().toString() + suffix;

        System.out.println(basePath + fileName);

        file.transferTo(new File(basePath + fileName));
//        file.transferTo(new File("D:\\test\\test.jpg"));

        Image image = new Image();
        image.setImage(fileName);
        image.setAddress(basePath+fileName);

        imageService.save(image);

        String []s={baseService+"upload/image/"+fileName, String.valueOf(image.getId())};

        return R.success(s);
//        return R.success("D:\\test\\test.jpg");
    }

    @GetMapping("/{name}")
    public void getById(@PathVariable("name") String name, HttpServletResponse response) throws IOException {

        FileInputStream inputStream=new FileInputStream(new File(basePath + name));

        System.out.println("图片地址:"+basePath + name);

        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("image/jpeg");

        int len;
        byte[] bytes = new byte[1024];

        while ((len=inputStream.read(bytes))!=-1){
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
    }
}
